<template>
  <div class="homepage-container">
    <div class="homepage-section homepage-background">
      <div class="homepage-login">
        <div class="login-container">
          <div class="login-title">
            <h1>享受视界，尽在视易</h1>
            <p>「在视易，打开多彩娱乐世界之门，畅享最丰富的影视、剧集、动漫等多元化娱乐 」</p>
          </div>
          <div class="mobile-login">
            <t-input
              type="tel"
              placeholder="请输入手机号"
              :maxlength="11"
              status="success"
              tips="目前仅支持中国大陆手机号码登录"
              v-model="mobile"
              size="large"
            >
              <template #prefix-icon>
                <t-icon name="mobile" size="24px" />
              </template>
              <template #suffix>
                <t-button @click="mobileLogin(mobile)">立即登录</t-button>
              </template>
            </t-input>
          </div>
          <div class="wx-login">
            <t-button variant="dashed" ghost theme="primary" @click="wxLogin">
              <template #icon>
                <t-icon name="logo-wechat" style="color: #07c160" />
              </template>
              微信登录
            </t-button>
            <p>支持PC、Pad、手机、浏览器、H5、微信小程序</p>
          </div>
        </div>
        <div class="homepage-person">
          <img v-lazy="srcPersonImg" class="person-img" alt="人物" />
        </div>
      </div>
    </div>
    <div class="homepage-section homepage-shop">
      <div class="shop-title all-title">
        <div class="title-wrap">
          <h1>十一号小铺</h1>
          <v-icon name="shangdian" style="margin-left: 1rem" />
        </div>
        <div class="shop-description">
          <p>「视易」有着影视、剧集、流媒体便捷之意</p>
        </div>
      </div>
      <div class="shop-card-container">
        <div
          v-for="(item, index) in cardList"
          :key="item.classId"
          class="main-home-card adapt-box"
          :class="cardClass(index)"
        >
          <!-- 判断当前是否是第一个card-shop容器 -->
          <div v-if="index === 0" class="shop-hot">
            <p>热销产品</p>
          </div>
          <div class="main-home-card-img">
            <img v-lazy="item.img" alt="" />
            <p class="main-home-card-num">已售： {{ item.num }}</p>
          </div>
          <div class="main-home-card-body">
            <div class="main-home-card-name">
              <span>「{{ item.name }}」</span>
              <div class="price-all">
                <span class="price"
                  >¥<strong>{{ item.price }}</strong
                  >/月</span
                >
              </div>
            </div>
            <div class="card-strip-warp">
              <div
                v-for="(strip, index) in item.stripList"
                :key="strip"
                class="main-home-card-strip"
                :class="getStripIndex(index)"
              >
                <check-icon class="icon-check" />
                <p>{{ strip }}</p>
              </div>
            </div>
          </div>
          <div class="main-home-btn">
            <t-button class="main-home-card-btn" @click="buy(item.classId)">快捷上车</t-button>
          </div>
        </div>
      </div>
    </div>
    <div class="homepage-share">
      <div class="share-title all-title">
        <div class="title-wrap">
          <h1>十一号星球</h1>
          <v-icon name="xingqiu" style="margin-left: 1rem" />
        </div>
        <div class="share-description">
          <p>"各大博主云集于此"</p>
        </div>
      </div>
      <div class="share-card-container" ref="container">
        <div class="share-card">
          <div class="prev-button">
            <t-button shape="circle" theme="primary" @click="rotateShareList(-1)">
              <template #icon><chevron-left-icon /></template>
            </t-button>
          </div>
          <div v-for="(item, index) in displayedShareList" :key="index" class="main-share-card">
            <div class="main-share-img">
              <img v-lazy="checkImage(item)" alt="" />
            </div>
            <div class="share-detail">
              <div class="main-share-name">
                <p>{{ item.name }}</p>
              </div>
              <t-divider />
              <div class="main-share-description">
                <p>{{ item.description }}</p>
              </div>
              <t-divider />
              <div class="main-share-fans">
                <p>粉丝：{{ item.fansCount }}</p>
              </div>
            </div>
            <t-button class="main-share-btn" @click="follow(item)">查看</t-button>
          </div>
          <div class="next-button">
            <t-button shape="circle" theme="primary" @click="rotateShareList(1)">
              <template #icon><chevron-right-icon /></template>
            </t-button>
          </div>
        </div>
      </div>
      <div class="share-data">
        <div class="data-title all-title">
          <div class="title-wrap">
            <h1>十一号数据库</h1>
            <v-icon name="shuju2" style="margin-left: 1rem" />
          </div>
        </div>
        <div class="share-data-container">
          <div class="data-card">
            <div v-for="(item, index) in dataCardList" :key="index" class="main-data-card">
              <div class="data-card-item-title">
                <div class="data-card-text">
                  <h3>{{ item.title }}{{ item.unit }}</h3>
                </div>
                <div class="data-card-image">
                  <v-icon :name="item.iconUrl" width="2.5rem" height="2.5rem" />
                </div>
              </div>
              <div class="data-value-container">
                <div class="data-value">
                  <strong>{{ item.value }}</strong>
                </div>
              </div>
              <div class="data-card-item-body">
                <p>
                  自上月以来<v-icon
                    :name="checkIsAdd(item)"
                    width="1.25rem"
                    height="1.25rem"
                    color="#fff"
                    style="margin-left: 0.25rem; margin-right: 0.25rem"
                  />{{ checkValue(item) }}{{ item.changeUnit }}
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <t-dialog
    :visible.sync="wxShow"
    :closeOnOverlayClick="false"
    :footer="false"
    :on-close="closeWxPay"
    :width="isMobilePhone ? '90%' : '600'"
  >
    <template #header>
      <h4>请使用微信扫码支付</h4>
    </template>
    <div>
      <img :src="'data:image/Jpeg;base64,' + payImg" alt="" />
    </div>
  </t-dialog>
  <t-dialog
    :visible="shopDialog"
    style="text-align: left"
    :on-close="closeUserDialog"
    :closeOnOverlayClick="false"
    :width="isMobilePhone ? '90%' : '600'"
  >
    <template #header>
      <div class="shop-dialog-header">
        <img :src="shopDialogImg" class="pay-img" />
        <div class="shop-header-price">
          <div class="popup-sku__goods-name">{{ className }}</div>
          <div class="goods-price-container">
            <span
              >¥<strong style="color: red; font-size: 27px">{{ price }}</strong></span
            >
            <p>库存:{{ stock }}</p>
          </div>
        </div>
      </div>
    </template>
    <template #footer>
      <div class="shop-dialog-footer">
        <t-button class="shop-dialog-btn" theme="primary" @click="aliPay">支付宝</t-button>
        <t-button class="shop-dialog-btn" theme="success" @click="wxBuy">微信</t-button>
      </div>
    </template>

    <h4 style="margin-bottom: 0.25rem">账号类型</h4>
    <t-radio-group
      v-model="accountType"
      variant="default-filled"
      size="large"
      @change="handleAccountTypeChange"
    >
      <t-radio-button
        v-for="(item, index) in dialogFirstCardList"
        :key="item.subjectId"
        :value="item.subjectId"
      >
        {{ item.name }}
      </t-radio-button>
    </t-radio-group>
    <div v-if="shopNotice" style="margin-top: 10px; padding: 0 10px">
      <t-icon name="error-circle-filled" style="color: #fa4126; font-size: 16px"></t-icon>
      <span
        style="
          font-size: 12px;
          margin-left: 5px;
          color: var(--td-text-color-primary);
          font-weight: bold;
          line-height: 16px;
        "
        >{{ shopNotice }}</span
      >
    </div>
    <t-divider style="margin-top: 8px; margin-bottom: 8px" />
    <h4 style="margin-bottom: 0.25rem" v-show="dialogSecondCardList.length > 0">账号分类</h4>
    <t-radio-group
      v-model="accountCategory"
      variant="default-filled"
      size="medium"
      @change="handleAccoutCategory"
      v-show="dialogSecondCardList.length > 0"
    >
      <t-radio-button
        v-for="(item, index) in dialogSecondCardList"
        :key="item.subjectId"
        :value="item.subjectId"
      >
        {{ item.name }}
      </t-radio-button>
    </t-radio-group>
    <t-divider
      style="margin-top: 8px; margin-bottom: 8px"
      v-show="dialogSecondCardList.length > 0"
    />
    <h4 style="margin-bottom: 0.25rem" v-show="dialogThirdCardList.length > 0">时长</h4>
    <div class="radio-button-group">
      <t-radio-group
        v-model="accountTime"
        variant="outline"
        size="small"
        @change="handleAccountTime"
        v-show="dialogThirdCardList.length > 0"
        style="width: 100%; display: flex; flex-wrap: wrap; justify-content: space-between"
        ><t-radio-button
          v-for="(item, index) in dialogThirdCardList"
          :key="item.subjectId"
          :value="item.subjectId"
          style="
            width: 45%;
            box-sizing: border-box;
            padding: 0 8px;
            margin-bottom: 8px;
            border-radius: 3px;
            border: 1px solid;
            border-color: var(--td-border-level-2-color);
            background-color: var(--td-bg-color-component);
            color: var(--td-text-color-secondary);
          "
        >
          {{ item.name }}
        </t-radio-button>
      </t-radio-group>
    </div>
    <t-divider style="margin-top: 10px" v-show="dialogThirdCardList.length > 0" />
    <t-form :model="form" labelWidth="0px">
      <t-form-item>
        <t-input
          label="优惠券"
          placeholder="请输入优惠券"
          v-show="dialogThirdCardList.length > 0"
          class="my-input-class"
          v-model:value="voucher"
          ><template #prefix-icon>
            <t-icon name="discount" />
          </template>
        </t-input>
      </t-form-item>
    </t-form>
  </t-dialog>
</template>

<script setup>
import { getTicketCategories, getTicketSubjects, createTicketOrder } from '@/api/ticket'
import { getShareCategories, getHomeData } from '@/api/home'
import { useThemeStore, useUserStore } from '@/store'
import { CheckIcon, ChevronRightIcon, ChevronLeftIcon } from 'tdesign-icons-vue-next'
import router from '@/router'
import { isWeixin, isMobile, watchIsMobile, checkIsMobile } from '@/utils/util'
import { checkWxPayStatusWebSocket, closeWebSocket } from '@/utils/websocket'
import {
  getAlipayPcPayment,
  getAlipayMobilePayment,
  getWeChatPaymentQrCode,
  getWxPrepayId
} from '@/api/payment'
import { MessagePlugin } from 'tdesign-vue-next'
import { getWxOpenId, getWxBaseOpenId, getWxAppId } from '@/utils/wxPay'
import { useRoute } from 'vue-router'
import { computed, onMounted, ref } from 'vue'
//主题store
const themeStore = useThemeStore()
const userStore = useUserStore()
const personImgDark = 'https://static.pluse.vip/assets/show-person-dark.webp'
const personImg = 'https://static.pluse.vip/assets/show-person.webp'
//检查是否是手机
const isMobilePhone = ref(checkIsMobile())
const voucher = ref('')
const form = ref({})
const cardList = ref([])
const shareList = ref([])
const container = ref(null)
let observer = null
const displayedShareList = ref([])
const currentIndex = ref(0)
const dataCardList = ref([])
let timer = null
const mobile = ref(null)
const accountType = ref('')
const accountCategory = ref('')
const accountTime = ref('')
const shopDialog = ref(false)
const firstCardList = ref([])
const secondCardList = ref([])
const thirdCardList = ref([])
const dialogFirstCardList = ref([])
const dialogSecondCardList = ref([])
const dialogThirdCardList = ref([])
const price = ref('')
const shopDialogImg = ref('')
const stock = ref('')
const orderCode = ref('')
const wxShow = ref(false)
const payImg = ref('')
const route = useRoute()
const openId = ref('')
const appId = ref('')
const timeStamp = ref('')
const nonceStr = ref('')
const packageStr = ref('')
const paySign = ref('')
const signType = ref('')
const className = ref('')
const shopNotice = ref('')

const onIsMobileChange = newIsMobile => {
  isMobilePhone.value = newIsMobile
}
onMounted(() => {
  const unwatch = watchIsMobile(onIsMobileChange)
  onBeforeUnmount(unwatch)
})

//关闭微信支付窗口
const closeWxPay = () => {
  wxShow.value = false
  closeWebSocket()
}
//微信支付
const wxBuy = () => {
  if (isWeixin()) {
    wxJsApiPay()
    return
  } else {
    wxNativePay()
  }
}
const wxJsApiPay = () => {
  //先判断WeixinJSBridge是否初始化成功
  if (typeof WeixinJSBridge == 'undefined') {
    if (document.addEventListener) {
      document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false)
    } else if (document.attachEvent) {
      document.attachEvent('WeixinJSBridgeReady', onBridgeReady)
      document.attachEvent('onWeixinJSBridgeReady', onBridgeReady)
    }
  } else {
    onBridgeReady()
  }
}
const onBridgeReady = async () => {
  //判断 appid 是否存在
  if (!appId.value) {
    //获取 appid
    const res1 = await getWxAppId()
    if (res1.code === 200) {
      //console.log('appId', res1.data)
      appId.value = res1.data
    }
  }

  //判断当前 url 有没有 code
  if (!route.query.code) {
    //没有code 重新获取code
    //  获取当前页面地址
    let url = window.location.href
    //获取授权地址
    const data = getData()
    let toUrl = getWxOpenId(appId.value, url, data)
    //console.log('toUrl', toUrl)
    window.location.href = toUrl
  }
}
const getAuthStatus = async () => {
  if (route.query.code) {
    //有code
    //console.log('有code')
    //获取code
    let code = route.query.code
    let state = JSON.parse(decodeURIComponent(route.query.state))

    //获取openid
    const res2 = await getWxBaseOpenId(code)
    if (res2.code === 200) {
      openId.value = res2.data
      //console.log('openId', res2.data)
      //创建订单
      //console.log('data', state)
      const res3 = await createTicketOrder(state)
      if (res3.code === 200) {
        orderCode.value = res3.data
        //获取预支付id
        const res4 = await getWxPrepayId({ orderCode: orderCode.value, openId: openId.value })
        if (res4.code === 200) {
          //console.log('res4', res4.data)
          timeStamp.value = res4.data.timeStamp
          nonceStr.value = res4.data.nonceStr
          packageStr.value = res4.data.prepayId
          paySign.value = res4.data.paySign
          signType.value = res4.data.signType
          appId.value = res4.data.appId
          wxPaySubmit()
        }
      }
    }
  }
}
onMounted(() => {
  getAuthStatus()
})

const toOrder = () => {
  setTimeout(() => {
    router.push({
      path: '/order',
      query: {
        orderCode: orderCode.value
      }
    })
  }, 3000)
}

const wxPaySubmit = () => {
  //调用 jsapi 支付
  let params = {
    appId: appId.value,
    timeStamp: timeStamp.value,
    nonceStr: nonceStr.value,
    package: packageStr.value,
    signType: signType.value,
    paySign: paySign.value
  }
  //判断微信浏览器是否初始化完成
  if (typeof WeixinJSBridge == 'undefined') {
    if (document.addEventListener) {
      document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady(params), false)
    } else if (document.attachEvent) {
      document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady(params))
      document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady(params))
    }
  } else {
    WeixinJSBridge.invoke('getBrandWCPayRequest', params, res => {
      if (res.err_msg == 'get_brand_wcpay_request:ok') {
        //支付成功
        MessagePlugin.success('支付成功')
        //跳转到订单详情
        // 将在 3 秒后跳转到订单详情
        toOrder()
      } else if (res.err_msg == 'get_brand_wcpay_request:cancel') {
        //支付取消
        MessagePlugin.error('支付取消')
      } else {
        //支付失败
        MessagePlugin.error('支付失败')
      }
    })
  }
}

const aliPay = async () => {
  const data = getData()

  await createTicketOrder(data).then(res => {
    if (res.code === 200) {
      shopDialog.value = false
      orderCode.value = res.data

      if (isMobile()) {
        // 移动设备走移动支付逻辑
        getAlipayMobilePayment({ orderCode: res.data }).then(res => {
          if (res.code === 200) {
            //3 秒后跳转支付宝支付
            MessagePlugin.success('3 秒后跳转支付宝支付!')
            // 创建定时器
            setTimeout(() => {
              const div = document.createElement('divAliPay')
              div.innerHTML = res.data
              document.body.appendChild(div)
              document.forms[1].submit()
            }, 3000)
          }
        })
      } else {
        // PC 设备走 PC 支付逻辑
        getAlipayPcPayment({ orderCode: res.data }).then(res => {
          if (res.code === 200) {
            //3 秒后跳转支付宝支付
            MessagePlugin.success('3 秒后跳转支付宝支付!')
            // 创建定时器
            setTimeout(() => {
              const div = document.createElement('divAliPay')
              div.innerHTML = res.data
              document.body.appendChild(div)
              document.forms[1].submit()
            }, 3000)
          }
        })
      }
    }
  })
}

const getData = () => {
  let data = {
    voucherId: voucher.value,
    subjectId: accountTime.value
  }

  return data
}
const wxNativePay = async () => {
  const data = getData()
  await createTicketOrder(data).then(res => {
    if (res.code === 200) {
      shopDialog.value = false
      orderCode.value = res.data

      // PC 设备走 PC 支付逻辑
      let data = {
        orderCode: res.data,
        type: 'pc'
      }
      //console.log('支付弹窗')
      getWeChatPaymentQrCode(data).then(res => {
        if (res.code === 200) {
          //console.log(res.data)
          payImg.value = res.data.img64
          wxShow.value = true
          checkWxPayStatusWebSocket(orderCode.value).then(res => {
            if (res.statusCode === 200) {
              wxShow.value = false
              MessagePlugin.success('支付成功!')
              toOrder()
            }
          })
        }
      })
    }
  })
}
const closeUserDialog = () => {
  shopDialog.value = false
}
/**
 * 初始化商品列表
 */
const initDisplayedShareList = () => {
  //根据屏幕大小显示不同的数量
  if (window.innerWidth >= 1101) {
    displayedShareList.value = shareList.value.slice(0, 4)
  } else if (window.innerWidth <= 1100 && window.innerWidth >= 769) {
    displayedShareList.value = shareList.value.slice(0, 2)
  } else {
    displayedShareList.value = shareList.value.slice(0, 1)
  }
}
//开始轮番
const startRotation = () => {
  if (!timer) {
    timer = setInterval(() => {
      rotateShareList(1)
    }, 5000)
  }
}
//停止轮番
const stopRotation = () => {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
}
// 根据索引设置分享列表的显示数量
const rotateShareList = direction => {
  currentIndex.value =
    (currentIndex.value + direction + shareList.value.length) % shareList.value.length
  const index = currentIndex.value
  const remainingItems = 4 - (shareList.value.length - index)
  //根据屏幕大小设置长度
  if (window.innerWidth >= 1101) {
    if (remainingItems > 0) {
      displayedShareList.value = [
        ...shareList.value.slice(index, index + 4),
        ...shareList.value.slice(0, remainingItems)
      ]
    } else {
      displayedShareList.value = shareList.value.slice(index, index + 4)
    }
  } else if (window.innerWidth <= 1100 && window.innerWidth >= 769) {
    displayedShareList.value = shareList.value.slice(index, index + 2)
  } else displayedShareList.value = shareList.value.slice(index, index + 1)
}
// onMounted 是执行初始化数据列表
onMounted(() => {
  initDisplayedShareList()
  //IntersectionObserver 是监听元素是否在视口内
  observer = new IntersectionObserver(
    entries => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          startRotation()
        } else {
          stopRotation()
        }
      })
    },
    {
      threshold: 0.5 // Adjust the threshold value based on your requirements
    }
  )

  if (container.value) {
    observer.observe(container.value)
  }
  window.addEventListener('resize', () => {
    initDisplayedShareList()
    rotateShareList(0)
  })
})
// onUnmounted 是销毁监听
onUnmounted(() => {
  if (observer && container.value) {
    observer.unobserve(container.value)
  }
  stopRotation()
  window.removeEventListener('resize', () => {
    initDisplayedShareList()
    rotateShareList(0)
  })
})
// isDarkMode 是判断当前主题模式
const isDarkMode = computed(() => {
  // 假设你有一个 `themeStore` 状态管理模块，
  // 并且 `mode` 属性表示当前主题模式。
  return themeStore.mode === 'dark'
})
// 监听本地存储的主题模式变化
const srcPersonImg = computed(() => {
  return isDarkMode.value ? personImgDark : personImg
})
// 根据索引判断商品背景是蓝色还是白色
const cardClass = index => {
  if (isMobilePhone) {
    return index % 2 === 0 ? 'blue' : 'white'
  } else {
    if (index % 4 === 0 || index % 4 === 3) {
      return 'blue'
    } else {
      return 'white'
    }
  }
}
onMounted(() => {
  // 获取传入的 subjectId 参数
  const route = useRoute()
  const classId = route.query.classId
  if (classId) {
    if (classId !== 0) {
      shopDialog.value = true
      getAndCacheTicketSubject(classId)
    }
  }
})

const getAndCacheTicketClass = async () => {
  const tiketClassStroge = sessionStorage.getItem('ticketClassList')
  try {
    // 如果已经缓存了数据，直接从缓存中获取
    if (tiketClassStroge) {
      cardList.value = JSON.parse(tiketClassStroge)
      return
    }
    const { data } = await getTicketCategories()
    data.sort((a, b) => {
      if (a.orderNo && b.orderNo) {
        return a.orderNo - b.orderNo
      } else if (a.orderNo) {
        return -1
      } else if (b.orderNo) {
        return 1
      } else {
        return b.soldNumber - a.soldNumber
      }
    })

    cardList.value = data.map(
      ({ classId, imageUrl: img, name, cost: price, soldNumber: num, serviceItem }) => ({
        classId,
        img,
        name,
        price,
        num,
        stripList: serviceItem.split(';')
      })
    )
    // 将请求到的数据缓存到 sessionStorage 中
    sessionStorage.setItem('ticketClassList', JSON.stringify(cardList.value))
  } catch (error) {
    //console.error(error)
  }
}

const handleAccountTypeChange = value => {
  // 根据 value 获取图片
  const item = dialogFirstCardList.value.find(item => item.subjectId === value)
  shopDialogImg.value = item.imgUrl
  shopNotice.value = item.subjectNotice
  //重新获取二级分类
  dialogSecondCardList.value = secondCardList.value.filter(item => item.parentId === value)
  if (dialogSecondCardList.value.length > 0) {
    // 更改 accountCategoryde 值
    accountCategory.value = dialogSecondCardList.value[0].subjectId
    handleAccoutCategory(accountCategory.value)
  } else {
    accountCategory.value = ''
    handleAccoutCategory(value)
  }
}
const handleAccoutCategory = value => {
  dialogThirdCardList.value = thirdCardList.value.filter(item => item.parentId === value)
  if (dialogThirdCardList.value.length > 0) {
    accountTime.value = dialogThirdCardList.value[0].subjectId
    handleAccountTime(accountTime.value)
  } else {
    dialogThirdCardList.value = thirdCardList.value.filter(item => item.parentId === value)
    if (dialogThirdCardList.value.length > 0) {
      accountTime.value = dialogThirdCardList.value[0].subjectId
      handleAccountTime(value)
    } else {
      accountTime.value = ''
    }
  }
}
const handleAccountTime = value => {
  //console.log('选中的值为：', value)
  //根据 value 值获取对应的数据
  const item = dialogThirdCardList.value.find(item => item.subjectId === value)
  price.value = item.price
  stock.value = item.stock
}

const buy = async classId => {
  if (!userStore.token) {
    MessagePlugin.error('请先登录')
    router.push('/login')
    return
  }
  dialogFirstCardList.value = []
  dialogSecondCardList.value = []
  dialogThirdCardList.value = []
  className.value = cardList.value.find(item => item.classId === classId).name
  shopDialog.value = true
  await getAndCacheTicketSubject(classId)
  //console.log(accountTime.value)
}
//获取子商品
const getAndCacheTicketSubject = async id => {
  const { data } = await getTicketSubjects({ classId: id })
  //console.log(data)
  firstCardList.value = data.firstLevelData
  dialogFirstCardList.value = data.firstLevelData
  secondCardList.value = data.secondLevelData
  thirdCardList.value = data.thirdLevelData

  //console.log(dialogFirstCardList.value)
  //console.log(dialogSecondCardList.value)
  //console.log(dialogThirdCardList.value)
  //初始化 1 级商品
  if (dialogFirstCardList.value.length > 0) {
    accountType.value = dialogFirstCardList.value.length
      ? dialogFirstCardList.value[0].subjectId
      : ''
  } else {
    accountType.value = ''
  }
  dialogSecondCardList.value = secondCardList.value.filter(
    item => item.parentId === accountType.value
  )
  if (dialogSecondCardList.value.length > 0) {
    accountCategory.value = dialogSecondCardList.value[0].subjectId
    // handleAccoutCategory(accountCategory.value)
  } else {
    accountCategory.value = ''
    dialogThirdCardList.value = thirdCardList.value.filter(
      item => item.parentId === accountType.value
    )
    if (dialogThirdCardList.value.length > 0) {
      accountTime.value = dialogThirdCardList.value[0].subjectId
      // handleAccountTime(accountTime.value)
    } else {
      accountTime.value = ''
    }
  }
  //排序
  dialogFirstCardList.value.sort((a, b) => a.orderNo - b.orderNo)
  dialogSecondCardList.value.sort((a, b) => a.orderNo - b.orderNo)
  dialogThirdCardList.value.sort((a, b) => a.orderNo - b.orderNo)
  if (accountType.value) {
    handleAccountTypeChange(accountType.value)
  }
}

getAndCacheTicketClass()
//获取分享
const getAndCacheShareList = async () => {
  const shareListStorage = sessionStorage.getItem('shareList')
  try {
    // 如果已经缓存了数据，直接从缓存中获取
    if (shareListStorage) {
      shareList.value = JSON.parse(shareListStorage)
      return
    }
    const { data } = await getShareCategories()
    data.sort((a, b) => {
      if (a.sortNo === b.sortNo) {
        return b.fansCount - a.fansCount
      } else {
        return b.sortNo - a.sortNo
      }
    })
    shareList.value = data

    // 将请求到的数据缓存到 sessionStorage 中
    sessionStorage.setItem('shareList', JSON.stringify(shareList.value))
  } catch (error) {
    //console.error(error)
  }
}
getAndCacheShareList()

//判断是增加还是减少
const checkIsAdd = item => {
  let iconName

  if (item.type === 'up') {
    iconName = 'shangsheng'
  } else if (item.type === 'down') {
    iconName = 'xiajiang'
  } else if (item.type === 'equal') {
    iconName = 'shangsheng'
  }
  return iconName
}
// 判断是否是NaN,是的话就返回0
const checkValue = item => {
  if (item.changeValue === 'NaN') {
    return '0'
  } else {
    return item.changeValue
  }
}
// 获取首页数据
const getAndCacheHomeData = async () => {
  const homeDataStorage = sessionStorage.getItem('homeData')
  try {
    // 如果已经缓存了数据，直接从缓存中获取
    if (homeDataStorage) {
      //console.log('从缓存中获取数据')
      dataCardList.value = JSON.parse(homeDataStorage)
      return
    }
    //console.log('从接口中获取数据')
    const { data } = await getHomeData()
    dataCardList.value = data
    // 将请求到的数据缓存到 sessionStorage 中
    sessionStorage.setItem('homeData', JSON.stringify(dataCardList.value))
  } catch (error) {
    //console.error(error)
  }
}

getAndCacheHomeData()
// 检测是否是本地图片
function checkImage(item) {
  if (item.avatarUrl.indexOf('http') === -1) {
    return import.meta.env.VITE_ASSETS_URL + item.avatarUri
  } else {
    return item.avatarUrl
  }
}
// 判断strip是第几个,根据索引返回不同的class
function getStripIndex(index) {
  return index + 1 === 1
    ? 'first'
    : index + 1 === 2
    ? 'second'
    : index + 1 === 3
    ? 'third'
    : 'fourth'
}
// 点击跳转
function follow(item) {
  //打开item内的link
  window.open(item.link)
}
//微信登录
const wxLogin = () => {
  const type = 'wx'
  //把url传到登录页面
  router.push({
    path: '/login',
    query: {
      type: type
    }
  })
}

//手机登录传参
const mobileLogin = mobile => {
  //校验手机号长度,不能小于 11 不能大于 11
  if (mobile.length !== 11) {
    MessagePlugin.error('请输入正确的手机号')
    return
  }
  //校验手机号是否合法
  if (
    !/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(mobile)
  ) {
    MessagePlugin.error('请输入正确的手机号')
    return
  }
  //把手机号缓存到sessionStorage
  sessionStorage.setItem('mobile', mobile)
  //把手机号传到登录页面
  router.push({
    path: '/login',
    query: {
      type: 'mobile',
      mobile: mobile
    }
  })
}
const handleMobile = () => {
  //获取手机号
  const cacheMobile = sessionStorage.getItem('mobile')
  //判断是否有手机号
  if (cacheMobile) {
    //有手机号就直接登录
    mobile.value = cacheMobile
    return
  }
  return
}
handleMobile()
</script>
<style lang="scss">
.radio-button-group {
  .t-is-checked {
    color: var(--td-text-color-primary) !important;
    background-color: var(--td-bg-color-container-select) !important;
    border: 2px solid !important;
    border-color: var(--td-border-level-2-color) !important;
  }
}
</style>

<style src="../style/home.scss" lang="scss" scoped></style>
